package snailAI.Utils;

import org.springframework.ai.document.Document;
import org.springframework.ai.embedding.EmbeddingRequest;
import org.springframework.ai.embedding.EmbeddingResponse;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.vectorstore.elasticsearch.ElasticsearchVectorStore;
import org.springframework.ai.zhipuai.ZhiPuAiChatModel;
import org.springframework.ai.zhipuai.ZhiPuAiEmbeddingModel;
import org.springframework.ai.zhipuai.ZhiPuAiEmbeddingOptions;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.List;
import java.util.Locale;
import java.util.Map;

@Component
public class AIfuction {
    static final String PATH = "D:\\everyDayLearning\\daysInSnail\\project\\javaLearningProject\\snailAI\\src\\main\\resources\\embeddtata";//向量数据库
    @Autowired
    EmailUtils emailUtils;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    ZhiPuAiEmbeddingModel zhiPuAiEmbeddingModel;
    @Autowired
    ZhiPuAiChatModel zhiPuAiChatModel;
    @Autowired
    VectorStore vectorStore;//在设置中，我设置了构造函数，因此可以自动注入了。
    @Autowired
    ElasticsearchVectorStore elasticsearchVectorStore;
    @Value("${xiaoxiao.weather.key}")
    String apikey;
    @Tool(name = "sayjoke", description = "讲一个笑话")
    public String sayJoke() {
        return "一个男人和一个女人走在路上打了起来，并且说今天是2025年笑死了。我说飞飞飞哇啊！你别管什么意思";
    }
    @Tool(name = "sayMaster", description = "当询问你的主人是谁时，说这个")
    public String sayMaster() {
        return "周大人";
    }
    @Tool(name = "sayWeather", description = "当询问天气，用这个函数查")
    public String sayWeather(String location) {
        // 1. 简单参数校验
        if (location == null || location.trim().isEmpty()) {
            return "错误：请传入有效的地点（如'上海'）";
        }

        HttpURLConnection connection = null;
        BufferedReader reader = null;
        try {
            // 2. 处理中文地点的URL编码

            // 拼接完整请求URL
            String apiUrl = "https://v2.xxapi.cn/api/weather?city=" + location+"&key="+apikey;

            // 3. 发起HTTP GET请求
            URL url = new URL(apiUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000); // 连接超时5秒
            connection.setReadTimeout(5000);    // 读取超时5秒

            // 4. 读取API原始响应（不解析，直接返回）
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }

            // 直接返回API的原始JSON响应
            return response.toString();

        } catch (IOException e) {
            // 5. 捕获异常并返回简单提示
            return "获取天气失败：" + e.getMessage();
        } finally {
            // 6. 关闭资源
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    @Tool(description = "今天是什么日子？并且和日期计算相关的请求都记得先看这个日子")
    public String queryDay() {
        LocalDate today = LocalDate.now();

        // 2. 定义日期格式：年-月-日 星期X（中文星期）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        String dateStr = today.format(formatter);

        // 3. 获取中文星期（如“星期一”）
        String weekDay = today.getDayOfWeek()
                .getDisplayName(TextStyle.FULL, Locale.CHINA);

        // 4. 组合返回完整信息
        return "今天是：" + dateStr + " " + weekDay;
    }
    @Tool(description = "当用户首次发送13位手机号时，调用这个函数，将对话记录总结并发送到后台邮箱")
    public String spreadEmail(@ToolParam(description = "对话记录，由AI总结，只拿取Content属性") String record,
                              @ToolParam(description = "客户的电话号") String phone
    ) {
        System.out.println("test---------------------");
        rabbitTemplate.convertAndSend(
                "emailFanoutExchange",
                "",
                "新的咨询人，大体情况如下：\n" +
                        record + "\n电话如下" + phone
        );
        return "好的，已经将相关消息发送到咨询老师了，老师正在看，过会老师会给您打电话的。";
    }
    @Tool(description = "当我想要存储蜗牛学苑的文档信息")
    public String savewoniu(@ToolParam(description = "用户想存入的消息") String msg) {
        try {
            // 1️⃣ 生成 embedding
            EmbeddingRequest request = new EmbeddingRequest(
                    List.of(msg),
                    ZhiPuAiEmbeddingOptions.builder()
                            .model("embedding-3")
                            .dimensions(2048)
                            .build()
            );
            EmbeddingResponse response = zhiPuAiEmbeddingModel.call(request);
            float[] embedding = response.getResult().getOutput();

            // 2️⃣ 构造 Document（必须有 text 字段）
            Document doc = Document.builder()
                    .text(msg)
                    .metadata(Map.of(
                            "source", "course_info",
                            "type", "courses.txt"
                    ))
                    .build();
            elasticsearchVectorStore.add(List.of(doc));
            return "礼貌地说已经存入了。";
        } catch (Exception e) {
            e.printStackTrace();
            return "存储失败：" + e.getMessage();
        }
    }
    @Tool(description =
     "当用户请求从向量数据库，或者数据库中搜索相似内容时（或要求查询相关文档时），总结返回。当用户说：给我xx的相关信息，也调用这个数据库")
    public String searchByVector
            (@ToolParam(description = "用户的查询问题")
            String query) {
        try {
            // 2️⃣ 用向量做搜索
            SearchRequest request = SearchRequest.builder()
                    .query(query)
                    .topK(6)
                    .similarityThreshold(0.4)
                    .build();
            List<Document> results = elasticsearchVectorStore.similaritySearch(request);

            if (results == null || results.isEmpty()) {
                return "我没有找到与此问题相似的知识内容。";
            }
            String ans="";
            for(Document x:results){
                ans+= x.getText();
                System.out.println(ans);
            }
            return ans;
        } catch (Exception e) {
            e.printStackTrace();
            return "向量搜索失败：" + e.getMessage();
        }
    }
}